package com.ptb.uranus.sms;

import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.ptb.uranus.sms.utils.JedisUtil;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

public class TaoBaoSDK {
	private static Logger logger = Logger.getLogger(TaoBaoSDK.class);
	static ResourceBundle bundle = PropertyResourceBundle.getBundle("ptb");
	public static void main(String[] args) {
		while(true){
			 String key = "ptb::sms";
			 byte[] ph = null;
	         try {
	         	ph=JedisUtil.rpop(key.getBytes());
	         } catch (Exception e) {
	             logger.error("[1000] redis is error", e);
	         }
	         //空消息则休息一段时间
	         if (ph == null) {
	             try {
	                 Thread.sleep(2000);
	             } catch (InterruptedException e) {
	             }
	             continue;
	         }
	         String s = null;
	            try {
	                s = new String(ph, "utf-8");
	            } catch (Exception e1) {
	                logger.error("Redis To obtain message for null!");
	            }
				try {
					JSONObject json = new JSONObject(s);
                    String phone = json.getString("phone");
                    String message = json.getString("message");
                    String type =null;
                    String smsFreeSignName=null;
                    switch (json.getInt("type")) {
					case 1:
						type = bundle.getString("sms.validation.type1");
						smsFreeSignName = bundle.getString("zeus.sms.taobao.SmsFreeSignName1");
						break;
					case 2:
						type=bundle.getString("sms.validation.type2");
						smsFreeSignName = bundle.getString("zeus.sms.taobao.SmsFreeSignName2");
						break;
					}
                    smsFreeSignName = new String(smsFreeSignName.getBytes("iso8859-1"),"UTF-8");
					TaobaoClient client = new DefaultTaobaoClient(bundle.getString("zeus.sms.taobao.sdk.uri"),bundle.getString("zeus.sms.taobao.AppKey"),bundle.getString("zeus.sms.taobao.AppSecret"));
					AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
					req.setSmsType("normal");
					req.setSmsFreeSignName(smsFreeSignName);
					req.setSmsParamString("{\"code\":\""+message+"\",\"product\":\"品推宝\"}");
					req.setRecNum(phone);
					req.setSmsTemplateCode(type);
					AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
					logger.info(rsp.getBody()+"   Message signatures is:"+smsFreeSignName);
				} catch (Exception e) {
					logger.error(String.format("[E] %s", s), e);
				}
	         
	         
		}
	}

}
